//
//  ZxViewController.m
//  维度科技
//
//  Created by 谷银行 on 2019/1/23.
//  Copyright © 2019 谷银行. All rights reserved.
//

#import "ZxViewController.h"
#import "NewPagedFlowView.h"// 轮播
#import "PGIndexBannerSubiew.h"// 头视图
#import "InformationTableViewCell.h" // 资讯Cell
#import "AdvertTableViewCell.h"//广告Cell

@interface ZxViewController ()<UITableViewDelegate,UITableViewDataSource,NewPagedFlowViewDelegate, NewPagedFlowViewDataSource>{
    NSMutableArray *imageArr;
}
@property(nonatomic , strong)UITableView *ojtable;
@property(nonatomic , copy)NSArray *Array;
@property(nonatomic , strong)NSMutableArray *Arr;
@property(nonatomic , copy)NSArray *SourceArray;;
@property(nonatomic , assign)NSInteger plateId;
/**
 *  图片数组
 */
@property (nonatomic, strong) NSMutableArray *imageArray;

/**
 *  轮播图
 */
@property (nonatomic, strong) NewPagedFlowView *pageFlowView;

@end

@implementation ZxViewController
- (UITableView *)ojtable{
    if (!_ojtable) {
        _ojtable = [[UITableView alloc]initWithFrame:self.view.frame style:UITableViewStylePlain];
        _ojtable.delegate = self;
        _ojtable.dataSource = self;
    }
    [_ojtable registerClass:[InformationTableViewCell class] forCellReuseIdentifier:@"cell"];
    return _ojtable;
}
- (void)viewDidLoad {
    [super viewDidLoad];
    [self Nav];
    [self TopAFNetWorking];
    [self CellLoadData];
    [self.view addSubview:self.ojtable];
}
// 导航条
- (void)Nav{
    // 标题
    self.navigationItem.title = @"资讯";
    // 左侧
    UIView *leftView = [[UIView alloc]init];
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc]initWithCustomView:leftView];
    leftView.sd_layout
    .leftSpaceToView(self.view, 0)
    .topSpaceToView(self.view, 0)
    .widthIs(24)
    .heightIs(24);
    UIButton *leftBtn = [[UIButton alloc]init];
    [leftView addSubview:leftBtn];
    leftBtn.sd_layout
    .leftSpaceToView(leftView, 0)
    .topSpaceToView(leftView, 0)
    .widthIs(24)
    .heightIs(24);
    [leftBtn setImage:[UIImage imageNamed:@"home_nav_btn_menu_n_hdpi"] forState:UIControlStateNormal];
    [leftBtn addTarget:self action:@selector(leftAction:) forControlEvents:UIControlEventTouchUpInside];
    //右侧
    UIView *rightView = [[UIView alloc]init];
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc]initWithCustomView:rightView];
    rightView.sd_layout
    .rightSpaceToView(self.view, 0)
    .topSpaceToView(self.view, 0)
    .widthIs(24)
    .heightIs(24);
    UIButton *rightBtn = [[UIButton alloc]init];
    [rightView addSubview:rightBtn];
    rightBtn.sd_layout
    .rightSpaceToView(rightView, 0)
    .topSpaceToView(rightView, 0)
    .widthIs(24)
    .heightIs(24);
    [rightBtn setImage:[UIImage imageNamed:@"common_nav_btn_search_n_hdpi"] forState:UIControlStateNormal];
    [rightBtn addTarget:self action:@selector(right) forControlEvents:UIControlEventTouchUpInside];
}
// 头视图请求
- (void)TopAFNetWorking{
    self.Array = [[NSArray alloc]init];
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    AFSecurityPolicy *securityPolicy = [AFSecurityPolicy defaultPolicy];
    securityPolicy.validatesDomainName = NO;
    securityPolicy.allowInvalidCertificates = YES;
    manager.securityPolicy = securityPolicy;

    [manager GET:@"https://172.17.8.100/techApi/information/v1/bannerShow" parameters:nil progress:^(NSProgress * _Nonnull downloadProgress) {
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        TopModel *model = [TopModel yy_modelWithJSON:responseObject];
        self.Array = model.result;
        [self.ojtable reloadData];
        [self performSelectorOnMainThread:@selector(TopView) withObject:nil waitUntilDone:NO];
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        NSLog(@"%@",error);
    }];
    
}
// 资讯内容请求
- (void)CellLoadData{
    self.SourceArray = [[NSArray alloc]init];
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObject:@"application/json"];
    AFSecurityPolicy *securityPolicy = [AFSecurityPolicy defaultPolicy];
    securityPolicy.validatesDomainName = NO;
    securityPolicy.allowInvalidCertificates = YES;
    manager.securityPolicy = securityPolicy;
    
    self.Arr = [[DataManager sharedDataHandle]getAllMovies];
    NSLog(@"+++++++%@",self.Arr);
    NSNumber *num = [NSNumber numberWithInt:[self.Arr[0]userId]];
    NSString *Sess = [self.Arr[0]sessionId];
    FLiewController *tk = [[FLiewController alloc] init];
    tk.plateIDBlock = ^(NSInteger plateBlock) {
       self.plateId = plateBlock;
    };
    NSNumber *platenum = [NSNumber numberWithInteger:self.plateId];
    NSDictionary *dic = @{
                          @"userId":num,
                          @"sessionId":Sess,
                          @"plateId":platenum,
                          @"page":@"1",
                          @"count":@"10"
                              };
    [manager GET:@"https://172.17.8.100/techApi/information/v1/infoRecommendList" parameters:dic progress:^(NSProgress * _Nonnull downloadProgress) {
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSLog(@"++++++++++++++++++%@",responseObject);
        InformationModel *model = [InformationModel yy_modelWithJSON:responseObject];
        self.SourceArray = model.result;
        [self.ojtable reloadData];
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        NSLog(@"%@",error);
    }];
    
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return self.SourceArray.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    InformationTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell"];

    InformationResultModel *model = self.SourceArray[indexPath.row];
    NSString *correctUrl = [model.thumbnail
                            stringByReplacingOccurrencesOfString:@"|" withString:@""];
    [cell.imgV sd_setImageWithURL:[NSURL URLWithString:correctUrl] placeholderImage:[UIImage imageNamed:@"h1"]];
    cell.TitleLabel.text = model.title;
    cell.contentLabel.text = model.summary;
//    NSString *time = [NSString stringWithFormat:@"%ld",(long)model.releaseTime];
    cell.timeLabel.text = model.source;
    NSString *shar = [NSString stringWithFormat:@"%ld",(long)model.share];
    cell.shareLabel.text = shar;
    return cell;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 130;
}
//导航右侧按钮
- (void)right{ 
    
}
//导航左侧按钮
- (void)leftAction:(UIButton *)sender
{
    FLiewController *Fenle = [FLiewController new];
    [self.navigationController pushViewController:Fenle animated:YES];
}
// 头视图
#pragma mark --滚动到指定的页数
- (void)gotoPage {
    
    //产生跳转的随机数
    int value = arc4random() % self.imageArray.count;
    NSLog(@"value~~%d",value);
    
    [self.pageFlowView scrollToPage:value];
}

- (void)TopView {
    NewPagedFlowView *pageFlowView = [[NewPagedFlowView alloc] init];
    pageFlowView.sd_layout
    .topSpaceToView(self.view, 8)
    .leftEqualToView(self.view)
    .heightIs(Width * 9 / 16)
    .widthIs(Width);
    pageFlowView.backgroundColor = [UIColor whiteColor];
    pageFlowView.delegate = self;
    pageFlowView.dataSource = self;
    pageFlowView.minimumPageAlpha = 0.4;
    pageFlowView.orginPageCount = self.imageArray.count;
    pageFlowView.isOpenAutoScroll = YES;
    
    UIScrollView *bottomScrollView = [[UIScrollView alloc] init];
    bottomScrollView.sd_layout
    .topSpaceToView(self.view, 8)
    .leftEqualToView(self.view)
    .heightIs(Width * 9 / 16)
    .widthIs(Width);
    [pageFlowView reloadData];
    [bottomScrollView addSubview:pageFlowView];
    self.ojtable.tableHeaderView = bottomScrollView;
    [bottomScrollView addSubview:pageFlowView];
    
    self.pageFlowView = pageFlowView;
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
    return (interfaceOrientation != UIInterfaceOrientationPortraitUpsideDown);
}

#pragma mark NewPagedFlowView Delegate
- (void)didSelectCell:(UIView *)subView withSubViewIndex:(NSInteger)subIndex {
    NSLog(@"点击了第%ld张图",(long)subIndex + 1);
}

#pragma mark NewPagedFlowView Datasource
- (NSInteger)numberOfPagesInFlowView:(NewPagedFlowView *)flowView {
    
    return self.Array.count;
}

- (UIView *)flowView:(NewPagedFlowView *)flowView cellForPageAtIndex:(NSInteger)index{
    
    PGIndexBannerSubiew *bannerView = (PGIndexBannerSubiew *)[flowView dequeueReusableCell];
    if (!bannerView) {
        bannerView = [[PGIndexBannerSubiew alloc] initWithFrame:CGRectMake(0, 0, Width, Width * 9 / 16)];
        bannerView.layer.cornerRadius = 4;
        bannerView.layer.masksToBounds = YES;
    }
    
    ResultModel *model = self.Array[index];
    NSURL *url = [NSURL URLWithString:model.imageUrl];
    NSData *data = [NSData dataWithContentsOfURL:url];
    bannerView.mainImageView.image = [UIImage imageWithData:data];
    UILabel *label1 = [[UILabel alloc]init];
    [bannerView addSubview:label1];
    label1.sd_layout
    .leftEqualToView(bannerView)
    .bottomEqualToView(bannerView)
    .widthIs(Width)
    .heightIs(40);
    label1.text = model.title;
    label1.backgroundColor = [UIColor redColor];
    label1.textColor = [UIColor whiteColor];
    label1.textAlignment = UITextAlignmentCenter;
    return bannerView;
}

- (void)didScrollToPage:(NSInteger)pageNumber inFlowView:(NewPagedFlowView *)flowView {
    
//    NSLog(@"TestViewController 滚动到了第%ld页",pageNumber);
}

#pragma mark --懒加载
- (NSMutableArray *)imageArray {
    if (_imageArray == nil) {
        _imageArray = [NSMutableArray array];
    }
    return _imageArray;
}

#pragma mark --旋转屏幕改变newPageFlowView大小之后实现该方法
- (void)viewWillTransitionToSize:(CGSize)size withTransitionCoordinator:(id)coordinator {
    
    if ([UIDevice currentDevice].userInterfaceIdiom == UIUserInterfaceIdiomPad)
    {
        [coordinator animateAlongsideTransition:^(id context) { [self.pageFlowView reloadData]; } completion:NULL];
    }
}

- (void)dealloc {
    
    /****************************
     在dealloc或者返回按钮里停止定时器
     ****************************/
    
    [self.pageFlowView stopTimer];
}
@end
